﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace Passwords.Biz
{
    public static class ValueUtil
    {
        public static DateTime StringToTime(this string value)
        {
            if (string.IsNullOrEmpty(value)) return DateTime.Now;
            try
            {
                return Convert.ToDateTime(value);
            }
            catch
            {
                return DateTime.Now;
            }
        }

        public static string TimeToString(this DateTime date)
        {
            string pattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortTimePattern;
            return date.ToString(pattern);
        }

        public static DateTime StringToDate(this string value)
        {
            if (string.IsNullOrEmpty(value)) return DateTime.Now;
            try
            {
                return Convert.ToDateTime(value).Date;
            }
            catch
            {
                return DateTime.Now;
            }
        }

        public static string DateToString(this DateTime date)
        {
            string pattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern;
            if (pattern.IndexOf("yyyy", StringComparison.InvariantCultureIgnoreCase) < 0)
            {
                pattern = pattern.Replace("yy", "yyyy");
            }
            return date.ToString(pattern);
        }

        public static DateTime StringToMonthYear(this string value)
        {
            if (string.IsNullOrEmpty(value)) return DateTime.Now;
            int len = value.Length;
            try
            {
                if (len != 5) return DateTime.Parse(value);
            }
            catch
            { }
            if (len != 5 && len != 7) throw new InvalidCastException();
            int m = int.Parse(value.Substring(0, 2));
            int y = int.Parse(value.Substring(3));
            if (y < 43) y += 2000; else if (y < 100) y += 1900;
            return new DateTime(y, m, 1);
        }


        public static string MonthYearToString(this DateTime dateTime)
        {
            return string.Format("{0:MM}/{0:yyyy}", dateTime);
            //return dateTime.ToString("y");
        }

        public static int StrToInt(this string value)
        {
            if (string.IsNullOrEmpty(value)) return 0;
            return Convert.ToInt32(value);
        }

        public static string IntToStr(this int value)
        {
            return value.ToString();
        }

    }
}
